<template>
  <div class="preserve-page">
    <div class="container">
      <div class="common-header">
        <div class="alibaba-design" />
        <div class="uncan-2019-text" />
        <div class="uncan-right" />
        <div class="title-status">
          <br>
          预约分论坛
        </div>
      </div>
      <div class="title-description" v-if="desc">
        {{desc}}
      </div>
      <div class="content" v-if="ready">
        <div class="tab-wrap">
          <div class="tab-item" :class="selectedGroupKey === groupKey ? 'active' : ''" v-for="(groupKey, index) in Object.keys(groupedData)" :key="index" @click="handleSelectGroup(groupKey)">
            {{groupKey}}
          </div>
        </div>
        <div class="options-wrap">
          <div v-for="(option, index) in groupedData[selectedGroupKey]" :class="optionClass(option)" :key="index" @click="handleSelect(option)">
            <div class="option-title">
              <div class="option-title-top">
                <div class="option-checkbox" />
                <div class="option-name">
                  {{option.meetingName}}
                </div>
                <div class="available-count">
                  <span v-if="isBreakoutFull(option)" class="available-count-small">已满</span>
                  <span v-else-if="option.labeling" class="breakout-tag">{{option.labeling}}</span>
                  <!-- <span class="available-count-big">
                  {{formatNum(option)}}
                </span> -->
                </div>
              </div>
              <div class="option-title-bottom">
                {{option.duration}} | {{option.address}}
              </div>
            </div>
            <div class="option-content">
              <pre>{{option.vnote}}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>
    <co-button class="preserve-action" :color="buttonColor" @click="handleSubmit" :loading="pending">
      {{Object.keys(selectedOptions).length ? `提交预约 (${Object.keys(selectedOptions).length})` : '提交预约'}}
    </co-button>
  </div>
</template>

<script>
import service from "../../api/preserve";

export default {
  name: "preserve",
  components: {
    // ticketCard,
    // totalPrice,
    // orderInfo,
    // payType,
    // flipDown,
    // acquireTicket
  },
  data() {
    return {
      projectId: "",
      selected: false,
      ready: false,
      desc: "",
      groupedData: {},
      selectedGroupKey: "",
      selectedOptions: {},
      pending: false
    };
  },
  computed: {
    buttonColor: function() {
      const sLength = Object.keys(this.selectedOptions).length;
      const gLength = Object.keys(this.groupedData).length;
      return sLength === gLength && Object.keys(this.groupedData).length
        ? "primary"
        : "disabled";
    }
  },
  created: function() {
    this.projectId = this.$route.params.projectId;
    service
      .getPreserveDesc({ projectId: this.projectId })
      .then(res => {
        const { data = "" } = res;
        this.desc = data;
      })
      .catch(err => {
        console.log(err);
      });
    service
      .getPreserveList({
        projectId: this.projectId,
        pageSize: "100",
        pageStart: "0"
      })
      .then(res => {
        // 前端按照日期分组
        const { data = [] } = res;
        const grouped = {};
        data
          .filter(item => item.status === 1)
          .sort((prev, next) => prev.startTime - next.startTime)
          .forEach(item => {
            const { startTime, endTime } = item;
            const groupKey = this.$moment(startTime).format("M月DD日");
            item.groupKey = groupKey;
            item.duration = `${this.$moment(startTime).format(
              "HH:ss"
            )} - ${this.$moment(endTime).format("HH:ss")}`;

            if (grouped[groupKey] && grouped[groupKey].length) {
              grouped[groupKey].push(item);
            } else {
              grouped[groupKey] = [item];
            }
          });

        console.log(grouped);
        this.groupedData = grouped;
        this.selectedGroupKey = Object.keys(grouped)[0];
        this.ready = true;
      })
      .catch(err => {
        console.log(err);
      });
  },
  methods: {
    optionClass(option) {
      return {
        option: true,
        checked: this.selectedOptions[option.groupKey] === option,
        disabled: option.inum - option.snum <= 0
      };
    },
    formatNum(option) {
      return option.inum - option.snum <= 0 ? 0 : option.inum - option.snum;
    },
    // 是否约满
    isBreakoutFull(option = {}) {
      return option.inum - option.snum <= 0;
    },
    handleSelectGroup(groupKey) {
      this.selectedGroupKey = groupKey;
    },
    handleSelect(option) {
      if (option.inum - option.snum <= 0) return;
      if (this.selectedOptions[option.groupKey] === option) {
        // 已选中的元素，取消选择
        delete this.selectedOptions[option.groupKey];
        this.selectedOptions = { ...this.selectedOptions };
      } else {
        // 该组已选过，切换选中元素
        // 该组未选过，增加key
        this.selectedOptions = {
          ...this.selectedOptions,
          [option.groupKey]: option
        };
      }
    },
    async handleSubmit() {
      if (
        Object.keys(this.selectedOptions).length !==
        Object.keys(this.groupedData).length
      ) {
        // 未选完整
        this.$toast(
          `需完整选择${
            Object.keys(this.groupedData).length
          }天的场次，每天选择一场`
        );
        return;
      }

      const result = await this.$confirm(
        "分论坛预约提交成功后将不可修改确认提交当前所选课程吗？",
        {
          title: "预约确认",
          okLabel: "确认",
          cancelLabel: "取消",
          showCancel: true
        }
      );

      if (!result) return;

      this.pending = true;
      const [option1, option2] = Object.keys(this.selectedOptions);
      return service
        .submitPreserve({
          projectId: this.projectId,
          branchIdOne: this.selectedOptions[option1].branchmeetingId,
          branchIdTwo: this.selectedOptions[option2].branchmeetingId
        })
        .then(res => {
          console.log(res);
          this.$router.go(-1);
        })
        .catch(err => {
          console.log(err);
          this.pending = false;
        });
    }
  }
};
</script>

<style scoped lang="scss">
.preserve-page {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
}

.breakout-tag {
  background-image: linear-gradient(-116deg, #ff6325 0%, #ed006f 100%);
  border-radius: 0 20.5px 20.5px 20.5px;
  padding: 2px 18px;
  font-size: 24px;
}

.preserve-action {
  height: 110px;
  width: 100%;
  border-radius: 0;
  flex-shrink: 0;
}
.container {
  flex: 1;
  width: 100%;
  height: 100%;
  min-height: 0;
  box-sizing: border-box;
  padding: 0 30px 120px;
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;

  .common-header {
    width: 100%;
    height: 321px;
  }

  .content {
    width: 100%;
    border-top: 1px solid #555;
    position: relative;

    .tab-wrap {
      position: relative;
      margin-bottom: 40px;
      height: 80px;
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;

      .tab-item {
        color: #f2f2f2;
        font-size: 28px;
        padding: 0 15px;
        font-weight: 500;
        position: relative;

        &.active {
          color: #0ce4a2;
          &:after {
            content: "";
            width: 100%;
            height: 4px;
            background: #0ce4a2;
            position: absolute;
            bottom: -18px;
            left: 0;
          }
        }
      }
    }

    .options-wrap {
      .option {
        width: 100%;
        border: 1px solid #5d5d5d;
        border-radius: 4px;
        margin-bottom: 16px;
        box-sizing: border-box;
        padding: 32px 24px 0;

        .option-title {
          position: relative;
          @include bottom-half-line();
          color: #fff;

          .option-title-top {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: left;
            position: relative;

            .option-checkbox {
              width: 39px;
              height: 39px;
              margin-right: 24px;
              border-radius: 39px;
              border: 1px solid #979797;
              position: relative;
            }

            .option-name {
              font-size: 30px;
              font-weight: 500;
            }

            .available-count {
              position: absolute;
              top: 0;
              right: 0;
              font-size: 32px;
              color: #eee;

              .available-count-small {
                font-size: 22px;
              }
            }
          }

          .option-title-bottom {
            box-sizing: border-box;
            width: 100%;
            padding: 16px 64px;
            font-size: 24px;
            color: #eee;
            text-align: left;
          }
        }

        .option-content {
          width: 100%;
          padding: 32px 64px;
          font-size: 24px;
          color: #eee;
          opacity: 0.6;
          text-align: left;
        }

        &.checked {
          background: linear-gradient(to right, #fd592c, #a802bd, #5803e4);
          border: none;
        }
        &.disabled {
          opacity: 0.5;
          .option-title-bottom {
            opacity: 0.8;
          }
        }
        &.checked .option-title .option-title-top .option-checkbox {
          background: url(https://img.alicdn.com/tfs/TB18bMbI4naK1RjSZFBXXcW7VXa-42-42.png)
            no-repeat;
          border: none;
          background-size: 100%;
        }
      }
    }
  }
}
</style>
